﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyBlog2.Models;
using MyBlog2.Repository;
using MyBlog2.ViewModels;


namespace MyBlog2.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Authorize]
    public class ArticleManageController : Controller
    {
        private readonly IArticleClassifyRepository _articleClassifyRepository;
        private readonly IArticleRepository _articleRepository;
        private readonly IUserRepository _userRepository;
        private AppDbContext _dbContext;
        private readonly ITagRepository _tagRepository;

        public ArticleManageController(AppDbContext dbContext, IArticleClassifyRepository articleClassifyRepository, IArticleRepository articleRepository, IUserRepository userRepository, ITagRepository tagRepository)
        {
            this._articleClassifyRepository = articleClassifyRepository;
            this._articleRepository = articleRepository;
            this._userRepository = userRepository;
            this._dbContext = dbContext;
            this._tagRepository = tagRepository;
        }


        /// <summary>
        /// 文章管理页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("Admin/ArticleManage/ArticleManage", Name = "ArticleManage")]
        public IActionResult ArticleManage(int pageIndex = 1, int pageSize = 10)
        {
            var articleList = _articleRepository.GetArticleList(pageIndex, pageSize, out int totalPageCount);
            ViewBag.pageCount = totalPageCount;
            ViewBag.pageIndex = pageIndex;
            return View(articleList);
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("Admin/ArticleManage/DeleteArticle", Name = "DeleteArticle")]
        public IActionResult DeleteArticle(int id)
        {
            _articleRepository.DeleteArticle(id);
            return Redirect("/Admin/ArticleManage/ArticleManage");
        }

        

        /// <summary>
        /// 搜索表单页
        /// </summary>
        /// <returns></returns>
        [ResponseCache(Duration = 600)]
        [Route("Admin/ArticleManage/SearchForm", Name = "SearchForm")]
        public IActionResult SearchForm()
        {
            ViewBag.classify = _articleClassifyRepository.GetArticleClassifieList();
            var qm = new ArticleQueryViewModel();
            return View(qm);
        }

        /// <summary>
        /// 搜索文章post
        /// </summary>
        /// <param name="articleQuery"></param>
        /// <returns></returns>
        [Route("Admin/ArticleManage/Search", Name = "Search")]
        [HttpPost]
        public IActionResult Search(ArticleQueryViewModel articleQuery)
        {
            if (articleQuery.QueryArticleClassifyId != -1 || string.IsNullOrEmpty(articleQuery.QueryArticleTitle))
            {
                var result = _articleRepository.SearchArticles(a => a.Title.Contains(articleQuery.QueryArticleTitle) || a.ArticleClassify.Id == articleQuery.QueryArticleClassifyId);
                ViewBag.resultCount = result.Count;
                return View(result);

            }
            else
            {
                return View("SearchForm");
            }

        }

        ///// <summary>
        ///// 文章搜索post (全匹配)
        ///// </summary>
        ///// <param name="articleQuery"></param>
        ///// <returns></returns>
        //[Route("Admin/ArticleManage/Search", Name = "Search")]
        //[HttpPost]
        //public IActionResult Search(ArticleQueryViewModel articleQuery)
        //{
        //    var result = _articleRepository.SearchArticles(new System.Collections.Generic.List<System.Linq.Expressions.Expression<System.Func<Models.Article, bool>>> { 
        //        a=>a.Title.Contains(articleQuery.QueryArticleTitle),
        //        a=>a.ArticleClassify.Id == articleQuery.QueryArticleClassifyId
        //    });
        //    ViewBag.resultCount = result.Count;
        //    return View(result);
        //}




        /// <summary>
        /// 添加文章页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("Admin/ArticleManage/AddArticle", Name = "AddArticle")]
        public IActionResult AddArticle()
        {
            ArticleViewModel articleViewModel = new ArticleViewModel {
                Article = new Article(),
                ArticleClassifies = _articleClassifyRepository.GetArticleClassifieList(),
                Tags = _tagRepository.GetTagList(),
            };
            return View(articleViewModel);
        }

        

        /// <summary>
        /// 添加文章 提交
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Admin/ArticleManage/AddArticlePost", Name = "AddArticlePost")]
        public IActionResult AddArticlePost([Bind("ArticleClassifyId,Title,Description,Contents,Flag,ShareStatement,CommentAbled,TagIds,Published")] Article article)
        {
            if (ModelState.IsValid && article.TagIds != null && article.TagIds != "")
            {
                article.CreateTime = DateTime.Now;
                article.UpdateTime = DateTime.Now;
                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    string userName = HttpContext.User.FindFirst(ClaimTypes.Name).Value;
                    article.User = _userRepository.GetUserByUsername(userName);
                }

                ICollection<ArticleTag> ats = new HashSet<ArticleTag>();
                string ids = article.TagIds;
                if (ids.Length == 1)
                {
                    ats.Add(new ArticleTag
                    {
                        ArticleId = article.Id,
                        Article = article,
                        TagId = Convert.ToInt32(ids),
                        Tag = _dbContext.Tags.FirstOrDefault(t => t.Id == Convert.ToInt32(ids))
                    });
                }
                if (ids.Length > 1)
                {
                    string[] strs = ids.Split(",");
                    for (int i = 0; i < strs.Length; i++)
                    {
                        ats.Add(new ArticleTag
                        {
                            ArticleId = article.Id,
                            Article = article,
                            TagId = Convert.ToInt32(strs[i]),
                            Tag = _dbContext.Tags.FirstOrDefault(t => t.Id == Convert.ToInt32(strs[i]))
                        });
                    }
                }
                
                article.ArticleTag = ats;


                var a = _articleRepository.AddArticle(article);
                if (a == null)
                {
                    return BadRequest("文章添加失败！");
                }
                
                return RedirectToRoute("ArticleManage");
            }
            else
            {
                return BadRequest("填写数据有误！");
            }
        }



        /// <summary>
        /// 文章编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("Admin/ArticleManage/EditArticle", Name = "EditArticle")]
        public IActionResult EditArticle(int id)
        {
            var article = _articleRepository.GetOneArticle(id);
            ViewBag.articleClassify = _articleClassifyRepository.GetArticleClassifieList();
            ViewBag.tags = _tagRepository.GetTagList();
            return View(article);
        }


        /// <summary>
        /// 编辑文章 提交
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Admin/ArticleManage/EditArticlePost", Name = "EditArticlePost")]
        public IActionResult EditArticlePost([Bind("Id,ArticleClassifyId,Flag,Title,Description,Contents,TagIds,ShareStatement,CommentAbled,Published")] Article article)
        {
            if (ModelState.IsValid && article.TagIds != null && article.TagIds != "")
            {
                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    string userName = HttpContext.User.FindFirst(ClaimTypes.Name).Value;
                    article.User = _userRepository.GetUserByUsername(userName);
                }

                ICollection<ArticleTag> ats = new HashSet<ArticleTag>();
                string ids = article.TagIds;
                if (ids.Length == 1)
                {
                    ats.Add(new ArticleTag
                    {
                        ArticleId = article.Id,
                        Article = article,
                        TagId = Convert.ToInt32(ids),
                        Tag = _dbContext.Tags.FirstOrDefault(t => t.Id == Convert.ToInt32(ids))
                    });
                }
                if (ids.Length>1)
                {
                    string[] strs = ids.Split(",");
                    for (int i = 0; i < strs.Length; i++)
                    {
                        ats.Add(new ArticleTag
                        {
                            ArticleId = article.Id,
                            Article = article,
                            TagId = Convert.ToInt32(strs[i]),
                            Tag = _dbContext.Tags.FirstOrDefault(t => t.Id == Convert.ToInt32(strs[i]))
                        });
                    }
                }
                
                article.ArticleTag = ats;

                var a = _articleRepository.EditArticle(article);
                if (a == null)
                {
                    return BadRequest("文章编辑失败！");
                }

                return RedirectToRoute("ArticleManage");
            }
            else
            {
                return BadRequest("填写数据有误！");
            }
        }
    }
}